#write by 李大宝
#in 2019,6,4

from flask import Flask, request,render_template,send_from_directory
from wtforms import FileField,Form,validators
from flask_wtf.file import file_allowed,file_required
import os

from werkzeug.utils import secure_filename
from werkzeug.datastructures import CombinedMultiDict

base_load=os.path.join(os.path.dirname(__file__),'images')
if not os.path.exists(base_load):
    os.mkdir(base_load)

app = Flask(__name__)

class file_down(Form):
    avatar=FileField(validators=[file_required(),file_allowed(['gif','png'])])


@app.route('/',methods=['GET','POST'])
def file_up():
    if request.method=='GET':
        return render_template('file_up.html')
    else:
        form=file_down(CombinedMultiDict([request.form,request.files]))
        if form.validate():
            avatar=request.files.get('avatar')
            filename=secure_filename(avatar.filename)
            avatar.save(os.path.join(base_load,filename))
            return '你的文件上传成功了'
        else:
            return '你的文件没有通过验证!'

@app.route('/get/<filename>')
def file_send(filename):
    return send_from_directory(base_load,filename)


if __name__=='__main__':
    app.run(debug=True)